02. componentDidMount Lifecycle Event

Use ComponentDidMount

How componentDidMount() Works

If you remember from the previous section, componentDidMount() is the lifecycle hook that is run right after the component is added to the DOM and should be used if you're fetching remote data or doing an Ajax request. Here's what the React docs have to say about it:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

Let's take a look at an example User component:

import React, { Component } from 'react';
import fetchUser from '../utils/UserAPI';

class User extends Component {
 constructor(props) {
   super(props);

   this.state = {
     name: '',
     age: ''
   };
 }

 componentDidMount() {
   fetchUser().then((user) => this.setState({
     name: user.name,
     age: user.age
   }));
 }

 render() {
   return (
     <div>
       <p>Name: {this.state.name}</p>
       <p>Age: {this.state.age}</p>
     </div>
   );
   }
}

export default User;

You'll notice that this component has a componentDidMount() lifecycle event. This component seems pretty straightforward, but let's walk through the order of how it works:

  1. The render() method is called which updates the page with a <div> that has one paragraph for the name and one paragraph for the age. What's important to realize is that this.state.name and this.state.age are empty strings (at first), so the name and age don't actually display
  • Once the component has been mounted, the componentDidMount() lifecycle event occurs
    • The fetchUser request from the UserAPI is run which sends a request to the user database
    • When the data is returned, setState() is called and updates the name and age properties
  • Since the state has changed, render() gets called again. This re-renders the page, but now this.state.name and this.state.age have values

Let's use componentDidMount() to fetch real users from a server in our Contacts app!

⚠️ Required API File ⚠️

At the beginning of the program, we gave you the option to clone our starter project or to start from scratch using create-react-app. If you used create-react-app to build your project, then you'll need the ContactsAPI file for the following video.

Use API To Fetch Remote Contacts

Where are Ajax requests made?

In which lifecycle method should you make Ajax/API requests?

SOLUTION: componentDidMount

Requests in render()?

Why shouldn't you make Ajax requests in the render method? Select all that apply:

SOLUTION:
  • `render()` method shouldn't be concerned with much more than just returning UI
  • You don't have complete control over when the `render()` method will be invoked

Task List:

Task Feedback:

Awesome work! Using componentDidMount is actually pretty easy, isn't it?

Remove Contacts

With what we have so far, we're fetching all users from the Contacts API and adding them to this.state.contacts. Pretty good so far. What's missing, though, is the removing feature. Currently, when we remove a contact, it gets removed from this.state.contacts, but it still exists in the backend database.

Let's use the Contacts API's remove() method to update the backend.

Remove Contacts

Lost All Your Contacts?

Now that we're syncing our contacts back to the server, any delete commands will remove all of them. Since we aren't able to add new ones yet, you'll be kinda stuck if you delete all of them.

To get the default list of contacts back, just restart your backend server. That's the backend server, not the Contacts app, itself.

Task List:

Task Feedback:

Great work following along here!

componentDidMount() Recap

componentDidMount() is one of a number of lifecycle events that React offers. componentDidMount() gets called after the component is "mounted" (which means after it is rendered). If you need to dynamically fetch data or run an Ajax request, you should do it in componentDidMount().

Further Research